package org.hotcore;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Date;

public class ServerHandler {
    public  void handleAccept(SelectionKey key) throws Exception{
        ServerSocketChannel ssc = (ServerSocketChannel)key.channel();
        SocketChannel clientSc = ssc.accept();
        clientSc.configureBlocking(false);
        clientSc.register( key.selector(),
                SelectionKey.OP_READ,
                ByteBuffer.allocate(1024));
    }

    public void handleRead(SelectionKey key) throws IOException {
        SocketChannel clientChannel =  (SocketChannel)key.channel();

        try
        {
            clientChannel.configureBlocking(false);
//       clientChannel.register( key.selector(),SelectionKey.OP_READ, );
            ByteBuffer byteBuffer =  (ByteBuffer) key.attachment();//ByteBuffer.allocateDirect(1024);//
            byteBuffer.clear();
            long byteRead = clientChannel.read(byteBuffer);
            if(byteRead == -1){
                clientChannel.close();//chcp 65001
            }else{
                byteBuffer.flip();
//           byte [] content = new byte[byteBuffer.limit()];
//           byteBuffer.get(content);
                String receivedString = Charset.forName("GBK").newDecoder()
                        .decode(byteBuffer).toString();
                //String receivedString = new String(byteBuffer.array());
                //String receiveMsg = new String(byteBuffer.array(),0,byteBuffer.limit());
                System.out.println("接收来自"
                        +clientChannel.socket().getRemoteSocketAddress()
                        +"的消息："+receivedString);
                String sendMsg = "你好客户端，我已经接收到你的信息";
                byteBuffer.clear();
                byteBuffer.put(sendMsg.getBytes(Charset.forName("GBK")));
                byteBuffer.flip();
                clientChannel.write(byteBuffer);
            }
        }catch (Exception e){
            e.printStackTrace();
            clientChannel.close();
        }


    }
}
